{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 监听程序只监听指定目录下在程序启动后新增的文件，不会去处理历史上已经存在的文件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from operator import add\n",
    "from pyspark import SparkContext\n",
    "from pyspark.streaming import StreamingContext"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "sc = SparkContext.getOrCreate()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "ssc = StreamingContext(sc, 20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-------------------------------------------\n",
      "Time: 2019-07-23 08:42:20\n",
      "-------------------------------------------\n",
      "\n",
      "-------------------------------------------\n",
      "Time: 2019-07-23 08:42:40\n",
      "-------------------------------------------\n",
      "('Stream', 1)\n",
      "('It', 1)\n",
      "('continuous', 2)\n",
      "('of', 3)\n",
      "('input', 2)\n",
      "('generated', 1)\n",
      "('Internally,', 1)\n",
      "('an', 1)\n",
      "('Each', 1)\n",
      "('in', 2)\n",
      "...\n",
      "\n",
      "-------------------------------------------\n",
      "Time: 2019-07-23 08:43:00\n",
      "-------------------------------------------\n",
      "('Stream', 1)\n",
      "('It', 1)\n",
      "('continuous', 2)\n",
      "('of', 3)\n",
      "('input', 2)\n",
      "('generated', 1)\n",
      "('Internally,', 1)\n",
      "('an', 1)\n",
      "('Each', 1)\n",
      "('in', 2)\n",
      "...\n",
      "\n",
      "-------------------------------------------\n",
      "Time: 2019-07-23 08:43:20\n",
      "-------------------------------------------\n",
      "\n"
     ]
    }
   ],
   "source": [
    "lines = ssc.textFileStream('file:///home/shilinlee/workspace/shilinlee/blog/spark_python/spark_streaming/log')\n",
    "words = lines.flatMap(lambda line: line.split(' '))\n",
    "wordCounts = words.map(lambda x : (x,1)).reduceByKey(add)\n",
    "wordCounts.pprint()\n",
    "ssc.awaitTermination()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
